package cn.b.sky.i18n.service.impl;

import cn.b.sky.i18n.dao.LocaleResourceTLDao;
import cn.b.sky.i18n.model.LocaleResourceTL;
import cn.b.sky.i18n.service.LocaleResourceTLService;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service("localeResourceTLService")
public class LocaleResourceTLServiceImpl implements LocaleResourceTLService {

  @Resource
  private LocaleResourceTLDao localeResourceTLDao;

  @Override
  public List<LocaleResourceTL> getlocaleResourceTLByCode(String siteCode, String resourceSet, String resourceKey,
      String sourceLanguage, String targetLanguage) {
    return localeResourceTLDao.getlocaleResourceTLByCode(siteCode, resourceSet, resourceKey, sourceLanguage,
        targetLanguage);
  }

  @Override
  public void saveLocaleResourceTLlist(String siteCode,List<LocaleResourceTL> list, String targetLanguage) {
    for (LocaleResourceTL tl : list) {
      tl.setSiteCode(siteCode);
      tl.setTargetLanguage(targetLanguage);
      if (StringUtils.isBlank(tl.getTargetLanguageText())) {
        localeResourceTLDao.deleteLocaleResourceTL(tl);
      }else if (null==localeResourceTLDao.selectlocaleResourceTL(tl)) {
        localeResourceTLDao.insertLocaleResourceTL(tl);
        //更新缓存
        LocaleResourceBundle
        .getBundle(tl.getSiteCode(), tl.getResourceSet(), tl.getTargetLanguage())
        .getResources().put(tl.getResourceKey(), tl.getResourceValue());
      }else {
        localeResourceTLDao.updateLocaleResourceTL(tl);
      //更新缓存
        LocaleResourceBundle
        .getBundle(tl.getSiteCode(), tl.getResourceSet(), tl.getTargetLanguage())
        .getResources().put(tl.getResourceKey(), tl.getResourceValue());
      }
    }
  }
}
